﻿using ExcelConfig.StoreAPI.helpers;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace ExcelConfig.StoreAPI._req
{
    internal class http_client
    {
        public static string Post(string url, string post_data)
        {
            string responseText = string.Empty;

            // 创建请求对象
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 30000; // 30秒超时

            // 写入请求体
            byte[] byteArray = Encoding.UTF8.GetBytes(post_data);
            request.ContentLength = byteArray.Length;

            using (var requestStream = request.GetRequestStream())
                requestStream.Write(byteArray, 0, byteArray.Length);

            // 获取响应
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                responseText = reader.ReadToEnd();
            return responseText;
        }
        public static HttpStatusCode JustPost(string url, string post_data)
        {
            // 创建请求对象
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 30000; // 30秒超时

            // 写入请求体
            byte[] byteArray = Encoding.UTF8.GetBytes(post_data);
            request.ContentLength = byteArray.Length;

            using (var requestStream = request.GetRequestStream())
                requestStream.Write(byteArray, 0, byteArray.Length);

            // 获取响应
            using (var response = (HttpWebResponse)request.GetResponse())
                return response.StatusCode;
        }
        public static Stream PostDownload(string url, string post_data, out string filename)
        {
            filename = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 30000; // 30秒超时

            // 写入请求体
            byte[] byteArray = Encoding.UTF8.GetBytes(post_data);
            request.ContentLength = byteArray.Length;

            using (var requestStream = request.GetRequestStream())
                requestStream.Write(byteArray, 0, byteArray.Length);


            using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            filename = GetDownloadFileName(response);
            var mem = new MemoryStream();
            using var reqstream = response.GetResponseStream();
            helper.ReadAllToMemory(reqstream, mem);
            mem.Position = 0;
            return mem;
        }
        public static string PostUpload(string url, multi_content content)
        {
            string responseText = string.Empty;

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            content.OnBuildingHeader(request);

            using (Stream requestStream = request.GetRequestStream()) content.WriteContent(requestStream);

            // 获取响应
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                responseText = reader.ReadToEnd();
            return responseText;
        }
        public static HttpStatusCode JustPostUpload(string url, multi_content content)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            content.OnBuildingHeader(request);

            using (Stream requestStream = request.GetRequestStream()) content.WriteContent(requestStream);

            // 获取响应
            using (var response = (HttpWebResponse)request.GetResponse())
                return response.StatusCode;
        }


        internal static string GetDownloadFileName(HttpWebResponse response)
        {
            string disposition = response.GetResponseHeader("Content-Disposition");
            if (string.IsNullOrEmpty(disposition)) return string.Empty;

            // 解析Content-Disposition头
            return ParseFileName(disposition);
        }

        internal static string ParseFileName(string disposition)
        {
            // 匹配filename参数（支持带引号和编码格式）
            var match = Regex.Match(disposition, @"filename\*?=['""]?([^'""]+)['""]?", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                string fileName = match.Groups[1].Value;

                // 处理RFC 5987编码格式（如filename*=UTF-8''%E6%96%87%E4%BB%B6.txt）
                if (fileName.StartsWith("UTF-8''", StringComparison.OrdinalIgnoreCase))
                {
                    fileName = Uri.UnescapeDataString(fileName.Substring(7));
                }
                else
                {
                    fileName = Uri.UnescapeDataString(fileName);
                }
                return fileName;
            }
            return string.Empty; // 默认文件名
        }
    }
}
